import axios from 'axios'
import { Toast } from 'vant'
import { getToken } from '@/utils/storage'
//二次封装axios
const request = axios.create({
    baseURL: 'http://hmmm.zllhyy.cn',
    timeout: 500000
})

export default request

//请求拦截器
request.interceptors.request.use(
  (config) => {
    //先判断接口请求数据中needToken是否为true，如果需要就加上token
    if (config.data?.needToken || config.params?.needToken) {
      config.headers = {
        ...config.headers,
        authorization: `Bearer ${getToken()}`,
      }
    }
    // if (getToken()) {
    //   // 请求拦截里统一携带token
    //   config.headers.authorization = `Bearer ${getToken()}`
    // }
    return config
},
  (error) => {
    return Promise.reject(error)
  }
)

//响应拦截器
request.interceptors.response.use(
    (response) => {
        const { code } = response.data
        if (code === 200) {
            return response.data
        } else {
            Toast.fail(response.data.message || '服务器错误')
            Promise.reject(response)
        }
    },
    (error) => {
        Toast.fail(error.data.message || '服务器错误')
        return Promise.reject(error)
    }
)
